package com.chen.winnerframework.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.chen.winnerframework.properties.OssProperties;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * oss工具类（阿里云）
 *
 * @author chengy
 * @date 2022/11/10
 */
public class OssUtil {

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件路径
     */
    public static String uploadFile(MultipartFile file, OssProperties properties) {
        String endpoint = properties.getEndpoint();
        String bucketName = properties.getBucketName();
        OSS ossClient = new OSSClientBuilder().build(endpoint, properties.getAccessKeyId(), properties.getAccessKeySecret());
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        try {
            InputStream inputStream = file.getInputStream();
            // 获取文件后缀索引
            int index = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(StrUtil.DOT);
            // 生成随机文件名
            String fileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(index);
            // 调用oss方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
            // 拼接文件路径 例如 https://test123.oss-cn-beijing.aliyuncs.com/01.jpg
            return "https://" + bucketName + StrUtil.DOT + endpoint + StrUtil.SLASH + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ObjectUtil.isNotNull(ossClient)) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名称
     */
    public static void deleteFile(String fileName, OssProperties properties) {
        OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(),
                properties.getAccessKeyId(), properties.getAccessKeySecret());
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(properties.getBucketName(), fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ObjectUtil.isNotNull(ossClient)) {
                ossClient.shutdown();
            }
        }
    }

}
